﻿using DeviceDetectorNET.Class.Device;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ThridGroup.ERP.DTO;
using ThridGroup.ERP.DTO.ProductionSystem;
using ThridGroup.ERP.ProductionSystem;
using ThridGroup.ERP.RBAC;
using Volo.Abp.Application.Dtos;

namespace ThridGroup.ERP.Web.Controllers.ProductionSystem
{

    [Route("OrderDispatch")]
    public class OrderDispatchController : Controller
    {
        private readonly IOrderDispatchServices _orderDispatchServices;
        private readonly UserIServices _userIServices;

        public OrderDispatchController(IOrderDispatchServices orderDispatchServices, UserIServices userIServices) 
        {
            _orderDispatchServices = orderDispatchServices;
            _userIServices = userIServices;
        }

        [HttpGet("OrderDispatchView")]
        public IActionResult OrderDispatchView()
        {
            return View();
        }
        /// <summary>
        /// 添加生产派单
        /// </summary>
        [HttpPost("AddOrderDispatch")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> AddOrderDispatch(CreateOrderDispatchDto input)
        {
            try
            {
                var id = await _orderDispatchServices.AddOrderDispatch(input);
                return Json(new { code = 0, msg = "添加成功", id });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "添加失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 获取生产派单分页列表
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="limit">每页数量</param>
        /// <param name="taskName">任务名称（可选）</param>
        /// <param name="productionOrderCode">生产工单编号（可选）</param>
        /// <param name="processesName">工序名称（可选）</param>
        /// <returns>返回分页后的生产派单及用户信息列表</returns>
        [HttpGet("GetOrderDispatchList")]
        public async Task<IActionResult> GetOrderDispatchList(int page = 1, int limit = 10, string taskName = null, string productionOrderCode = null, string processesName = null)
        {
           

            try
            {
                dynamic result = await _orderDispatchServices.GetOrderDispatchList(page, limit, taskName, productionOrderCode, processesName);
                return Json(new { code = 0, msg = "success", count = result.TotalCount, data = result.Items });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取列表失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 显示用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("ShowUser")]
        public async Task<JsonResult> ShowUser([FromQuery] ShowUserDTO showUserDTO)
        {
            var user = await _userIServices.ShowUser(showUserDTO);
            var result = user.OrderByDescending(m => m.Id).Skip((showUserDTO.PageIndex - 1) * showUserDTO.PageSize).Take(showUserDTO.PageSize).ToList();
            return Json(new
            {

                code = 0,
                msg = "",
                count = user.Count,
                data = result
            });
        }

        /// <summary>
        /// 生成生产工单编号
        /// </summary>
        [HttpGet("GenerateProductionOrderCode")]
        public IActionResult GenerateProductionOrderCode()
        {
            try
            {
                // 生成格式：GD + 年月日 + 4位随机数
                var today = DateTime.Now;
                string productionOrderCode = "GD" + today.ToString("yyyyMMdd") + new Random().Next(1000, 9999).ToString();

                return Json(new { code = 0, productionOrderCode = productionOrderCode });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "生成生产工单编号失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 检查生产工单编号是否已存在
        /// </summary>
        [HttpGet("CheckProductionOrderCodeExists")]
        public async Task<IActionResult> CheckProductionOrderCodeExists(string productionOrderCode)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(productionOrderCode))
                {
                    return Json(new { code = 1, msg = "生产工单编号不能为空" });
                }

                var result = await _orderDispatchServices.GetOrderDispatchList(1, 1, null, productionOrderCode, null);
                bool exists = result.TotalCount > 0;

                return Json(new { code = 0, exists = exists });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "检查生产工单编号失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 批量删除生产派单
        /// </summary>
        [HttpPost("BatchDelete")]
        public async Task<IActionResult> BatchDelete([FromBody] List<int> ids)
        {
            var count = await _orderDispatchServices.BatchDeleteAsync(ids);
            return Json(new { code = 0, msg = $"成功删除{count}条记录" });
        }

        /// <summary>
        /// 批量反填生产派单详情
        /// </summary>
        [HttpPost("BatchGetByIds")]
        public async Task<IActionResult> BatchGetByIds([FromBody] List<int> ids)
        {
            var result = await _orderDispatchServices.GetByIdsAsync(ids);
            return Json(new { code = 0, msg = "success", data = result });
        }

        /// <summary>
        /// 根据ID获取生产派单详情（反填）
        /// </summary>
        [HttpGet("GetById")]
        public async Task<IActionResult> GetById(int id)
        {
            var result = await _orderDispatchServices.GetByIdAsync(id);
            return Json(new { code = 0, msg = "success", data = result });
        }

        /// <summary>
        /// 更新单个生产派单
        /// </summary>
        [HttpPost("Update")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Update(CreateOrderDispatchDto dto)
        {
            var count = await _orderDispatchServices.UpdateAsync(dto);
            return Json(new { code = 0, msg = "修改成功", count });
        }

        /// <summary>
        /// 批量更新生产派单
        /// </summary>
        [HttpPost("BatchUpdate")]
        public async Task<IActionResult> BatchUpdate([FromBody] List<CreateOrderDispatchDto> dtos)
        {
            var count = await _orderDispatchServices.BatchUpdateAsync(dtos);
            return Json(new { code = 0, msg = $"成功更新{count}条记录" });
        }

        /// <summary>
        /// 删除单个生产派单
        /// </summary>
        [HttpPost("Delete")]
        public async Task<IActionResult> Delete(int id)
        {
            var count = await _orderDispatchServices.DeleteAsync(id);
            return Json(new { code = 0, msg = "删除成功", count });
        }






    }
}
